﻿using RuiXinCoffee.BLL;
using RuiXinCoffee.Model;
using RuiXinCoffee.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RuiXinCoffee.UI
{
    public partial class CartForm : BaseForm
    {
        private string selectedOption = "";
        private RadioButton rbDineIn;
        private RadioButton rbTakeOut;
        private readonly OrderInfo orderInfo;

        public CartForm()
        {
            try
            {
                InitializeComponent();
                InitializeCartPanel();
                
                //从数据库加载待付款订单
                ShoppingCartService.Instance.LoadPendingOrders();
                
                ShoppingCartService.Instance.CartUpdated += SetupProductDisplay;
                SetupProductDisplay();
                this.FormClosing += MyForm_FormClosing;
                lblTotal.Text = $"￥{ShoppingCartService.Instance.CalculateTotal()}";
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭窗口时不需要做任何处理，订单状态由支付按钮控制
            //待付款订单将保留在数据库中，直到用户支付或删除
        }

        private void InitializeCartPanel()
        {
            try
            {
                GroupBox gbDelivery = new GroupBox
                {
                    Text = "取餐方式",
                    Font = new Font("幼圆", 13),
                    Size = new Size(500, 150),
                    Location = new Point(10, 10)
                };
                panel2.Controls.Add(gbDelivery);

                //店内用餐选项  
                rbDineIn = new RadioButton
                {
                    Text = "店内用餐",
                    Font = new Font("幼圆", 11),
                    Size = new Size(180, 100),
                    Location = new Point(20, 50),
                    AutoSize = true,
                    Checked = true
                };
                gbDelivery.Controls.Add(rbDineIn);

                //自提带走选项  
                rbTakeOut = new RadioButton
                {
                    Text = "自提带走",
                    Font = new Font("幼圆", 11),
                    Size = new Size(180, 100),
                    Location = new Point(20, 100),
                    AutoSize = true
                };
                gbDelivery.Controls.Add(rbTakeOut);
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("初始化取餐面板失败", ex));
            }
        }

        private void SetupProductDisplay()
        {
            try
            {
                panel1.Controls.Clear();

                panel1.Size = new Size(660, 420);
                panel1.BackColor = ColorTranslator.FromHtml("#D7E4F2");
                panel1.BorderStyle = BorderStyle.FixedSingle;
                panel1.Padding = new Padding(14);
                panel1.AutoScroll = true;

                int topPosition = 5;

                foreach (OrderInfo orderInfo in ShoppingCartService.Instance.Orders)
                {
                    //创建单个商品面板
                    Panel panel2 = new Panel();
                    panel2.Size = new Size(panel1.ClientSize.Width - 50, 170);
                    panel2.Location = new Point(15, topPosition);
                    panel2.BackColor = ColorTranslator.FromHtml("#D7E4F2");
                    panel2.BorderStyle = BorderStyle.FixedSingle;
                    panel2.Padding = new Padding(10);

                    //产品图片
                    var pictureBox = new PictureBox
                    {
                        Size = new Size(120, 120),
                        Location = new Point(15, (panel2.Height - 120) / 2),
                        SizeMode = PictureBoxSizeMode.Zoom,
                        BorderStyle = BorderStyle.FixedSingle,
                        Tag = "product-image"
                    };

                    pictureBox.Image = ImageHelper.LoadImage(orderInfo.ProductImageUrl);
                    panel2.Controls.Add(pictureBox);

                    //产品名称
                    var lblName = new Label
                    {
                        Text = orderInfo.ProductName,
                        Font = new Font("幼圆", 12, FontStyle.Bold),
                        ForeColor = Color.FromArgb(45, 45, 45),
                        AutoSize = false,
                        Size = new Size(220, 40),
                        Location = new Point(pictureBox.Right + 20, 15),
                        TextAlign = ContentAlignment.MiddleLeft
                    };
                    panel2.Controls.Add(lblName);

                    //分隔线
                    var separator = new Panel
                    {
                        Height = 1,
                        BackColor = Color.Silver,
                        Location = new Point(pictureBox.Right + 20, lblName.Bottom + 5),
                        Width = panel2.Width - pictureBox.Right - 40
                    };
                    panel2.Controls.Add(separator);

                    string cup = orderInfo.CupType switch
                    {
                        0 => "中杯",
                        1 => "大杯",
                        2 => "超大杯",
                        _ => "超大杯"
                    };

                    string ice = string.IsNullOrEmpty(orderInfo.IceLevel) ? "正常冰" : orderInfo.IceLevel;
                    string sweet = string.IsNullOrEmpty(orderInfo.SugarLevel) ? "正常糖" : orderInfo.SugarLevel;

                    //规格参数
                    var lblParameters = new Label
                    {
                        Text = $"杯型: {cup}\n甜度: {sweet}\n冰度: {ice}",
                        Font = new Font("幼圆", 10),
                        ForeColor = Color.FromArgb(100, 100, 100),
                        Size = new Size(130, 100),
                        Location = new Point(pictureBox.Right + 20, separator.Bottom + 10),
                        TextAlign = ContentAlignment.MiddleLeft
                    };
                    panel2.Controls.Add(lblParameters);

                    //单价显示
                    var lblPrice = new Label
                    {
                        Text = $"¥{orderInfo.Price.ToString()}",
                        Font = new Font("幼圆", 14, FontStyle.Bold),
                        ForeColor = ColorTranslator.FromHtml("#6E3B00"),
                        Size = new Size(150, 40),
                        Location = new Point(panel2.Width - 160, 20),
                        TextAlign = ContentAlignment.MiddleRight
                    };
                    panel2.Controls.Add(lblPrice);

                    //数量控制与总价
                    var lblQuantity = new Label
                    {
                        Text = $"数量: {orderInfo.Quantity}",
                        Location = new Point(panel2.Width - 100, lblPrice.Bottom + 10),
                        Size = new Size(100, 30)
                    };
                    panel2.Controls.Add(lblQuantity);

                    //添加到主面板
                    panel1.Controls.Add(panel2);

                    //更新垂直位置
                    topPosition += panel2.Height + 15;
                }

                //如果没有商品，显示提示
                if (ShoppingCartService.Instance.Orders.Count == 0)
                {
                    var emptyLabel = new Label
                    {
                        Text = "购物车为空，请添加商品",
                        Font = new Font("幼圆", 14, FontStyle.Italic),
                        Dock = DockStyle.Fill,
                        TextAlign = ContentAlignment.MiddleCenter,
                        ForeColor = Color.Gray
                    };
                    panel1.Controls.Add(emptyLabel);
                }
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("显示购物车商品失败", ex));
            }
        }

        private void payButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (ShoppingCartService.Instance.Orders.Count == 0)
                {
                    throw new UserOperationException("购物车为空，请先添加商品");
                }

                //检查取餐方式
                if (!rbDineIn.Checked && !rbTakeOut.Checked)
                {
                    throw new UserOperationException("请选择取餐方式");
                }

                //创建支付成功窗体
                PaymentSuccessForm successForm = new PaymentSuccessForm();
                
                //更新所有订单为已支付状态
                if (ShoppingCartService.Instance.UpdateAllOrdersAsPaid())
                {
                    successForm.ShowDialogWithBinding(this);
                }
                else
                {
                    throw new BusinessException("支付失败，请重试");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        public class PaymentSuccessForm : BaseForm
        {
            public PaymentSuccessForm()
            {
                InitializeSuccessForm();
            }

            private void InitializeSuccessForm()
            {
                try
                {
                    this.Text = "支付成功";
                    this.Size = new Size(500, 350);
                    this.BackColor = Color.White;
                    this.StartPosition = FormStartPosition.CenterScreen;
                    this.FormBorderStyle = FormBorderStyle.FixedDialog;
                    this.MaximizeBox = false;
                    this.MinimizeBox = false;

                    Label successLabel = new Label
                    {
                        Text = "支付成功!",
                        Font = new Font("幼圆", 20, FontStyle.Bold),
                        ForeColor = Color.FromArgb(0, 150, 0),
                        AutoSize = true,
                        Location = new Point(150, 80)
                    };

                    Label messageLabel = new Label
                    {
                        Text = "您的订单已支付成功，感谢您的购买!\n订单号: " + GenerateOrderNumber(),
                        Font = new Font("幼圆", 12),
                        TextAlign = ContentAlignment.MiddleCenter,
                        AutoSize = false,
                        Size = new Size(450, 60),
                        Location = new Point(25, 150)
                    };

                    Button okButton = new Button
                    {
                        Text = "确 定",
                        Size = new Size(150, 40),
                        Location = new Point(175, 210),
                        BackColor = Color.FromArgb(0, 150, 136),
                        ForeColor = Color.White,
                        Font = new Font("幼圆", 12, FontStyle.Bold),
                        FlatStyle = FlatStyle.Flat,
                        Cursor = Cursors.Hand
                    };
                    okButton.FlatAppearance.BorderSize = 0;
                    okButton.Click += (s, e) => this.Close();

                    this.Controls.Add(successLabel);
                    this.Controls.Add(messageLabel);
                    this.Controls.Add(okButton);
                }
                catch (Exception ex)
                {
                    HandleException(new BusinessException("初始化支付成功窗口失败", ex));
                }
            }

            private string GenerateOrderNumber()
            {
                try
                {
                    //生成订单号：当前日期+4位随机数
                    string datePrefix = DateTime.Now.ToString("yyyyMMdd");
                    string randomSuffix = new Random().Next(1000, 9999).ToString();
                    return $"ORD{datePrefix}-{randomSuffix}";
                }
                catch (Exception)
                {
                    return "ORD20231001-0001"; //备用订单号
                }
            }
        }
    }
}
